package com.hhf.ds.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author haohaifeng
 * @date 2021/1/15 16:22
 */
@Slf4j
public class ExportUtils {

    private final static String CHARSET_UTF8 = "UTF-8";
    private final static Integer flushCount = 1000;
    /**
     * 文件写入excel
     * @param file 文件
     * @param list 数据源
     * @param sheetname 工作簿
     * @throws IOException
     */
    @Deprecated
    public static void exportExcel(File file, List<Map<String,Object>> list, String sheetname) throws IOException {
        Workbook wb = new XSSFWorkbook(FileUtils.openInputStream(file));
        Sheet sheet = wb.getSheet(sheetname);
        Row row = sheet.getRow(1);
        if (row == null) {
            row = sheet.createRow(1);
        }
        Map<String, Object> m =list.get(0);
        String [] title = new String[m.size()];
        int v = 0;
        for(String key : m.keySet()){
            title[v] = key;
            v++;
        }
        FileOutputStream fos = new FileOutputStream(file);
        for (int i = 0; i < list.size(); i++) {
            row = sheet.createRow(i + 1);
            Map<String, Object> map = list.get(i);
            for (int j = 0; j < title.length; j++) {
                row.createCell((short) j).setCellValue(map.get(title[j]) + "");
            }
        }
        wb.write(fos);
        fos.flush();
        fos.close();
    }

    /**
     * 导出报表Excel到浏览器.
     * @param response
     * @param fileName
     * @param list
     * @param titleCols
     * @throws IOException
     */
    public static void exportExcel(HttpServletResponse response, String fileName, List<Map<String,String>> list, String[] titleCols) throws IOException {
        SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
        SXSSFSheet sheet = workbook.createSheet();
        Row row = sheet.createRow(0);
        for (int i=0;i<titleCols.length; i++) {
            row.createCell((short) i).setCellValue(titleCols[i]);
        }
        if (list != null && !list.isEmpty()) {
            Map<String, String> m =list.get(0);
            if (titleCols.length != m.size() ) {
                log.error("表头字段列数和数据字段列数不相等");
            }
            String [] title = new String[m.size()];
            int v = 0;
            for(String key : m.keySet()) {
                title[v] = key;
                v++;
            }
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                Map<String, String> map = list.get(i);
                for (int j = 0; j < title.length; j++) {
                    String value = map.get(title[j]);
                    row.createCell((short) j).setCellValue(value== null ? "" : value);
                }
            }
        }
        write(response, fileName, workbook);
    }

    private static void write(HttpServletResponse response, String fileName, Workbook workbook) throws IOException {
        response.setContentType("application/octet-stream");
        String encodedName = URLEncoder.encode(fileName+ ".xlsx", CHARSET_UTF8);
        response.setHeader("Content-Disposition", "attachment;filename=\"" + encodedName + "\";filename*=utf-8''" + encodedName);
        response.setHeader("filename",encodedName);
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setDateHeader("Expires", (System.currentTimeMillis() + 1000));
        response.setStatus(HttpStatus.OK.value());
        ServletOutputStream os = response.getOutputStream();
        workbook.write(os);
        os.close();
        response.flushBuffer();
        workbook.close();
    }
}
